<?
/**
* Класс для работы с базой данных
*/
class Database{
	static public $host, $user_name, $user_pass, $database_name;
	static private $connection = null;
	static private $last_result = null;
	static private $last_query = "";

	static public function staticConstruct(){
		//инициализация статических переменных класса
	}

	static public function connect(){
		if(!is_null(self::$connection)) return self::$connection;
		$r = @mysql_connect(self::$host, self::$user_name, self::$user_pass);
		if (!$r) 
			throw new Exception("Невозможно соединиться с MySQL ".mysql_error());
		if(!mysql_select_db(self::$database_name))
			throw new Exception(mysql_error());
		self::$connection = $r;
		return $r;
	}
	
	static public function disconnect(){
		if(is_null(self::$connection)) return;
		mysql_close(self::$connection);
		self::$connection = null;
	}

	static public function query($sql){
		self::$last_query = $sql;
		self::$last_result = mysql_query($sql);
		$err = mysql_error();
		if ($err !== '')
		{
			throw new Exception($err);
			return false;
		}
		return self::$last_result;
	}

	static public function rowCount(){ 
		return mysql_num_rows(self::$last_result); 
	}

	static public function fetchRow(){
		if(!self::$last_result) return false;
		if(!is_resource(self::$last_result)) return false;
		return mysql_fetch_assoc(self::$last_result);
	}

	static public function fetchAll(){
		$ret = array();
		while($row = self::fetchRow()) $ret[] = $row;
		return $ret;
	}

	static public function getInsertID(){
		return mysql_insert_id();
	}

	static public function selectAndFetch($sql){
		self::query($sql);
		$row = self::fetchRow();
		if(empty($row)) return false;
		return reset($row);
	}
	
	static public function select($sql, $simplify = false){
		self::query($sql);
		$rows = self::fetchAll();
		if($simplify) Arr::arraySimplify($rows);
		return $rows;
	}
	
	static public function fetchObject($class_name = false){
		$table_name = self::getTableName(self::$last_query);
		$row = self::fetchRow();
		if(empty($row)) return false;
		if(!$class_name) $class_name = 'tbl_'.$table_name;
		$obj = new $class_name();
		$obj->setData($row);
		return $obj;
	}
	
	static public function fetchObjects($class_name = false){
		$objects = array();
		while($one = self::fetchObject($class_name)){
			$objects[] = $one;
		}
		return $objects;
	}
	
	static public function getTableName($sql){
		if(!preg_match('/.*?\sFROM\s+(\S+\s*\.\s*)?(\S+)\s*/i', $sql, $mat)) return false;
		$table_name = $mat[2];
		$table_name = trim($table_name, " `");
		return $table_name;
	}

    static public function getAffectedRows(){
        return mysql_affected_rows();
    }
	
}

Database::staticConstruct();
?>
